﻿#ifndef __SS_CHAR_CODING_H__
#define __SS_CHAR_CODING_H__
#include "ConvertUTF.h"
#include <string>

namespace StarSeeker
{

	bool UTF8_To_UNICODE(const std::string& inStr, std::wstring & outStr)
	{
		size_t widesize = inStr.length();
		if (sizeof(wchar_t) == 2)
		{
			outStr.resize(widesize + 1, L'\0');
			const UTF8* sourcestart = reinterpret_cast<const UTF8*>(inStr.c_str());
			const UTF8* sourceend = sourcestart + widesize;
			UTF16* targetstart = reinterpret_cast<UTF16*>(&outStr[0]);
			UTF16* targetend = targetstart + widesize;
			ConversionResult res = ConvertUTF8toUTF16(&sourcestart, sourceend, &targetstart, targetend, strictConversion);
			if (res != conversionOK)
			{
				return false;
			}
			*targetstart = 0;
			return true;
		}
		else if (sizeof(wchar_t) == 4)
		{
			outStr.resize(widesize + 1, L'\0');
			const UTF8* sourcestart = reinterpret_cast<const UTF8*>(inStr.c_str());
			const UTF8* sourceend = sourcestart + widesize;
			UTF32* targetstart = reinterpret_cast<UTF32*>(&outStr[0]);
			UTF32* targetend = targetstart + widesize;
			ConversionResult res = ConvertUTF8toUTF32(&sourcestart, sourceend, &targetstart, targetend, strictConversion);
			if (res != conversionOK)
			{
				return false;
			}
			*targetstart = 0;
			return true;
		}
		return false;
	}

	bool UNICODE_To_UTF8(const std::wstring& inStr, std::string& outStr)
	{
		size_t widesize = inStr.length();

		if (sizeof(wchar_t) == 2)
		{
			size_t utf8size = 3 * widesize + 1;
			outStr.resize(utf8size, '\0');
			const UTF16* sourcestart = reinterpret_cast<const UTF16*>(inStr.c_str());
			const UTF16* sourceend = sourcestart + widesize;
			UTF8* targetstart = reinterpret_cast<UTF8*>(&outStr[0]);
			UTF8* targetend = targetstart + utf8size;
			ConversionResult res = ConvertUTF16toUTF8(&sourcestart, sourceend, &targetstart, targetend, strictConversion);
			if (res != conversionOK)
			{
				return false;
			}
			*targetstart = 0;
			return true;
		}
		else if (sizeof(wchar_t) == 4)
		{
			size_t utf8size = 4 * widesize + 1;
			outStr.resize(utf8size, '\0');
			const UTF32* sourcestart = reinterpret_cast<const UTF32*>(inStr.c_str());
			const UTF32* sourceend = sourcestart + widesize;
			UTF8* targetstart = reinterpret_cast<UTF8*>(&outStr[0]);
			UTF8* targetend = targetstart + utf8size;
			ConversionResult res = ConvertUTF32toUTF8(&sourcestart, sourceend, &targetstart, targetend, strictConversion);
			if (res != conversionOK)
			{
				return false;
			}
			*targetstart = 0;
			return true;
		}
		return false;
	}

}
#endif
